package com.skynet.supervision.aop.uac;

import cn.hutool.core.bean.BeanUtil;
import com.skynet.supervision.aop.uac.beans.UACUserInfo;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Nonnull;
import javax.annotation.Resource;
import java.util.Optional;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 *
 * @author xuchao
 * @date 2023-03-08 20:48
 */
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private UACClientProperties property;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UACUserInfo.class)
                && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(@Nonnull MethodParameter parameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  @Nonnull NativeWebRequest request,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {

        if (BeanUtil.isNotEmpty(this.property)
                && Optional.ofNullable(this.property.getEnable()).orElse(false)) {
            return request.getAttribute(AuthorizationInterceptor.USER_KEY, RequestAttributes.SCOPE_REQUEST);
        }
        return null;
    }
}
